﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;


namespace MotivLogger
{
    public class XmlSettings : SettingsProvider
    {
        public Dictionary<string, string> GetDictionary(string ModuleName, ISetting setting)
        {

            XmlDocument config = new XmlDocument();
            config.Load(Application.StartupPath + "\\logconfig.xml");
            XmlNode conf = config.SelectSingleNode("/configuration/" + ModuleName);
            Dictionary<string, string> settings = new Dictionary<string, string>((conf != null) ? conf.ChildNodes.Count : 0);
            if (conf != null && conf.ChildNodes.Count != 0)
            {
                foreach (XmlNode child in conf.ChildNodes)
                {
                    if (child.ChildNodes.Count > 0)
                    {
                        setting.AddChild(child.Name);
                    }
                    else
                        settings.Add(child.Attributes["key"].Value, child.Attributes["value"].Value);

                }
            }
            return settings;

        }
        public static void SerializeSettings(string FileName)
        {
            XmlDocument doc = new XmlDocument { XmlResolver = null };
            doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><configuration></configuration>");
            XmlElement conf = doc.DocumentElement;
            foreach (KeyValuePair<string, Settings> s in Settings.modules)
            {
                XmlElement module = doc.CreateElement(s.Key);
                foreach (KeyValuePair<string, string> item in s.Value.items)
                {
                    XmlElement i = doc.CreateElement("item");
                    i.SetAttribute("key", item.Key);
                    i.SetAttribute("value", item.Value);
                    module.AppendChild(i);
                }
                conf.AppendChild(module);

            }
            doc.AppendChild(conf);
            doc.Save(System.IO.Path.Combine(Application.StartupPath, FileName));
        }
    }
}
